package megalopolis.client;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import megalopolis.model.Building;
import megalopolis.model.GameObject;
import megalopolis.model.Man;

/**
 * User: Kirill
 * Date: 19.02.2008
 */
public class GameCanvas extends Canvas implements View {

    private Controller controller;

	public GameCanvas(Controller controller) {
        this.controller = controller;

		addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent e) {
				GameCanvas.this.controller.keyPressed(e.getKeyCode());
			}
		});
    }

	public void updateMap() {
		repaint();
	}

	public void paint(Graphics g) {
		super.paint(g);

		if (controller == null || !controller.isLogined()) {
			// maybe draw demo
			return;
		}
		
		Man playerMan = controller.getPlayerMan();

		if (playerMan == null) {
			// temporary situation, we have already logined but haven't received any MapUpdatedResponse
			return;
		}

		GameMap map = controller.getGameMap();
		for (GameObject gameObject : map.getGameObjects()) {
			if (gameObject instanceof Man) {
				drawMan(g, playerMan, (Man) gameObject);
			} else if (gameObject instanceof Building) {
				drawBuilding(g, playerMan, (Building) gameObject);
			}
		}
	}

	private void drawMan(Graphics g, Man playerMan, Man man) {
		int x = getX(man.x, playerMan);
		int y = getY(man.y, playerMan);
		int radius = 5;

		g.drawOval(x - radius / 2, y - radius / 2, radius, radius);
	}

	private void drawBuilding(Graphics g, Man playerMan, Building building) {
		int x1 = getX(building.x, playerMan);
		int y1 = getY(building.y, playerMan);
		int x2 = getX(building.x + building.width, playerMan);
		int y2 = getY(building.y + building.height, playerMan);

		g.drawRect(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x2 - x1), Math.abs(y2 - y1));
	}

	private int getX(int x, Man playerMan) {
		return getWidth() / 2 + x - playerMan.x;
	}

	private int getY(int y, Man playerMan) {
		return getHeight() / 2 - y + playerMan.y;
	}
}
